package com.webchartserver.core.intercetes;

import com.alibaba.fastjson.JSON;
import com.webchartserver.core.config.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 模块名称：是否登录过的拦截器（用于验证token是否有效）
 * 模块类型：拦截器
 * 编码人：高靖博
 * 创建时间：2023/4/14
 * 联系电话：18587388612
 */
public class LoginInterceptor implements HandlerInterceptor {

    // 请求访问controller方法之前会指向性

    /**
     *
     * @param request http请求对象
     * @param response http响应对象
     * @param handler 执行链路对象
     * @return 返回值： true： 拦截器放行 false：拦截器阻止
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        // 所有的token都要放在请求头中  header
        String token = request.getHeader("token");

        //验证
        if(token==null||token==""){

            Map<String,String> json = new HashMap<>();
            json.put("msg","认证失败，token不存在！");
            json.put("code","-1");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(json));
            writer.flush();
            writer.close();
            return false;
        }else{// 验证

            boolean verify = JWTUtil.verify(token);

            if(verify){
                return true;
            }else{
                Map<String,String> json = new HashMap<>();
                json.put("msg","认证失败！");
                json.put("code","-1");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(json));
                writer.flush();
                writer.close();
                return false;
            }
        }
    }
}
